// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import GameEvent from "../../Commons/GameEvent";
import TaskManager, { TaskEvent } from "../../Models/Tasks/TaskManager";
import BaseUI from "../BaseUI";
import TaskItem from "../UIItems/TaskItem";

const { ccclass, property } = cc._decorator;

@ccclass
export default class TaskUI extends BaseUI {

    @property(cc.ScrollView)
    scrollview: cc.ScrollView = null;
    @property(cc.Prefab)
    taskItemPrefab: cc.Prefab = null;
    @property(cc.Button)
    allReceiveBtn: cc.Button = null;

    protected onLoad(): void {
        for (let i = 0; i < 10; i++) {
            var taskNode = cc.instantiate(this.taskItemPrefab);
            taskNode.active = false;
            this.scrollview.content.addChild(taskNode);

        }
    }

    protected onEnable(): void {
        this.drawView();
        this.allReceiveBtn.interactable = TaskManager.single.isHaveReceive();
        GameEvent.eventNode.on(TaskEvent.RECEIVETASKREWARD_EVENT, this.onUpdataView, this);
    }

    protected onDisable(): void {
        GameEvent.eventNode.off(TaskEvent.RECEIVETASKREWARD_EVENT, this.onUpdataView, this);
    }
    onUpdataView() {
        this.drawView();
    }
    drawView(): void {
        var childs = this.scrollview.content.children;
        for (let i = 0; i < childs.length; i++) {
            const element = childs[i];
            element.active = true;
            var taskItem = element.getComponent(TaskItem);
            var taskArr = TaskManager.single.getTaskListByType(101 + i);
            taskItem.drawItem(taskArr);
        }
    }

    allReceiveClick() {
        while (TaskManager.single.isHaveReceive()) {
            for (let i = 0; i < 10; i++) {
                var taskArr = TaskManager.single.getTaskListByType(101 + i);
                var taskEy = TaskManager.single.getTaskEntity(taskArr[0].taskType);
                if (taskEy != null && !taskEy.rewards[taskEy.nestRewardIndex] && taskEy.taskPregress >= taskArr[taskEy.nestRewardIndex].targetNum) {
                    TaskManager.single.requestReceiveTaskReward(taskArr[0].taskType, taskEy.nestRewardIndex);
                }
            }
        }
        this.allReceiveBtn.interactable = TaskManager.single.isHaveReceive();
    }
}
